<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mold:fal:asdMoldFal:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    @close="closeDrawer"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #invSelect>
        <ListSelect
          ref="listSelectRef"
          v-model:value="invCode"
          :labelValue="invName"
          :selectList="selectListRef"
          :selectType="'invSelect'"
        />
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        :formKey="formKey"
        completeText="提交"
        :loading="loadingRef"
        :auth="'mold:repair:asdMoldUpdate:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoldFalAsdMoldFalForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { AsdMoldUpdate, asdMoldUpdateForm } from '/@/api/mold/repair/asdMoldUpdate';

  import { AsdMoldFal, asdMoldFalSave, asdMoldFalForm } from '/@/api/mold/fal/asdMoldFal';
  import { asdMoldKeepForm } from '/@/api/mold/keep/asdMoldKeep';
  import { operTreeData } from '/@/api/bas/oper';
  import { ListSelect } from '/@/components/ListSelect';
  import { officeTreeData } from '/@/api/sys/office';
  import { BpmButton } from '/@/components/Bpm';
  import { bpmGetTask } from '/@/api/bpm/task';

  const emit = defineEmits(['success', 'register']);

  const formKey = ref<string>('ASD_MOLD_REPAIR');
  const procInsName = ref<string>('');

  const selectListRef = ref<Recordable[]>([]);
  const listSelectRef = ref<any>(null);
  const invCode = ref<string>('');
  const invName = ref<string>('');
  const selectedValue = ref<string>('');
  const loadingRef = ref(false);

  const { t } = useI18n('mold.fal.asdMoldFal');
  const { showMessage } = useMessage();
  const record = ref<AsdMoldFal>({} as AsdMoldFal);
  const recordAsdMoldUpdate = ref<AsdMoldUpdate>({} as AsdMoldUpdate);
  console.log('router.currentRoute', router.currentRoute);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('首件确认') + '(' + procInsName.value + ')',
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('维修记录ID'),
      field: 'hid',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      show: false,
    },
    {
      label: t('工装编码'),
      field: 'moldCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('工装尾号'),
      field: 'lastNum',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('工序名称'),
      field: 'basMold.operCode',
      component: 'Input',
      dynamicDisabled: true,
      // fieldLabel: 'oper.operName',
      // component: 'TreeSelect',
      // componentProps: {
      //   api: operTreeData,
      //   allowClear: true,
      // },
    },
    {
      label: t('存货代码'),
      field: 'cinvaddcode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {},
    },
    {
      label: t('存货编码'),
      field: 'cinvcode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {},
    },
    {
      label: t('存货名称'),
      field: 'cinvcode',
      fieldLabel: 'cinvname',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'invSelect',
          params: { isAll: true },
          canSelectParent: false,
          allowClear: true,
          onSelect: (value, node) => {
            formModel['cinvaddcode'] = value[0].cinvaddcode;
          },
        }
      },
      dynamicDisabled: true,
    },
    {
      label: t('故障信息'),
      field: 'gzMsg',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('维修者'),
      field: 'repairName',
      fieldLabel: 'empUser.userName',
      component: 'TreeSelect',
      componentProps: {
        // api: empUserTreeData,
        api: officeTreeData,
        allowClear: true,
        params: { isLoadUser: true, userIdPrefix: '' },
        canSelectParent: false,
        treeCheckable: false,
      },
      dynamicDisabled: true,
    },
    {
      label: t('登记日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      dynamicDisabled: true,
    },
    {
      label: t('维修日期'),
      field: 'repairDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      dynamicDisabled: true,
    },
    {
      label: t('维修时长'),
      field: 'repairTime',
      component: 'Input',
      componentProps: {
        placeholder: t('单位：小时'),
        addonAfter: '小时',
      },
      dynamicDisabled: true,
    },
    {
      label: t('维修描述'),
      field: 'repairDescription',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('确认状态'),
      field: 'falStatus',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'mold_fal_status',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('确认人名称'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
      show: false
    },
  ];


  const inputFormKeepSchemas: FormSchema[] = [
    {
      label: t('工装名称'),
      field: 'moldCode',
      fieldLabel: 'basMold.name',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'moldSelect',
          onSelect: async (values) => {
            console.log(values);
            formModel['moldCode'] = values[0].code;
            formModel['lastNum'] = values[0].lastNum;
            formModel['basMold.caddcode'] = values[0].caddcode;
            formModel['basMold.clsCode'] = values[0].clsCode;

            formModel['useQty'] = values[0].useQty;
            formModel['byQty'] = values[0].byQty || 0;
            formModel['iqty'] = values[0].byQty - values[0].useBlQty;
          },
        };
      },
      dynamicDisabled: true,
      required: true,
    },
    {
      label: t('工装代码'),
      field: 'basMold.caddcode',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('工装类型'),
      field: 'basMold.clsCode',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('工装尾号'),
      field: 'lastNum',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      // required: true,
    },
    // {
    //   label: t('存货代码'),
    //   field: 'cinvaddcode',
    //   component: 'Input',
    //   dynamicDisabled: true,
    //   componentProps: {},
    // },
    // {
    //   label: t('存货编码'),
    //   field: 'cinvcode',
    //   component: 'Input',
    //   dynamicDisabled: true,
    //   componentProps: {},
    // },
    // {
    //   label: t('存货名称'),
    //   field: 'cinvcode',
    //   fieldLabel: 'cinvname',
    //   component: 'ListSelect',
    //   componentProps: ({ formModel }) => {
    //     return {
    //       selectType: 'invSelect',
    //       params: { isAll: true },
    //       canSelectParent: false,
    //       allowClear: true,
    //       onSelect: (value, node) => {
    //         formModel['cinvaddcode'] = value[0].cinvaddcode;
    //       },
    //     }
    //   },
    //   dynamicDisabled: true,
    // },
    {
      label: t('加工次数'),
      field: 'useQty',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('保养周期'),
      field: 'byQty',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('剩余寿命'),
      field: 'iqty',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('保养时长'),
      field: 'keepTime',
      component: 'InputNumber',
      componentProps: {
        placeholder: t('单位：小时'),
        addonAfter: '小时',
      },
      dynamicDisabled: true,
    },
    {
      label: t('保养内容'),
      field: 'keepDesc',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
    },
    {
      label: t('送保人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      show: false,
    },
    {
      label: t('模具保养人'),
      field: 'repairName',
      fieldLabel: 'empUser.userName',
      component: 'TreeSelect',
      componentProps: {
        // api: empUserTreeData,
        api: officeTreeData,
        allowClear: true,
        params: { isLoadUser: true, userIdPrefix: '' },
        canSelectParent: false,
        treeCheckable: false,
      },
      dynamicDisabled: true,
    },
    {
      label: t('确认状态'),
      field: 'falStatus',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'mold_fal_status',
        allowClear: true,
      },
      required: true,
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, resetSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });
  //     schemas: formKey.value === 'ASD_MOLD_REPAIR' ? inputFormSchemas : inputFormKeepSchemas,

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    console.log(data,'data');
    formKey.value = data.bizKey;
    setDrawerProps({ loading: true });
    await resetFields();
    const task = await bpmGetTask({
      id:data['bpm.taskId'],
      'procIns.bizKey': data.id,
    })
    if(String(formKey.value) == 'undefined') {
      formKey.value = task?.procIns?.formKey;
    }
    // const procInsFormKey = task?.procIns?.formKey;
    procInsName.value = task?.procIns?.procDef?.name;


    console.log('formKey', String(formKey.value) == 'ASD_MOLD_REPAIR');
    if (String(formKey.value) == 'ASD_MOLD_REPAIR') {
      console.log('inputFormSchemas', inputFormSchemas);
      const resFalForm = await asdMoldUpdateForm(data);
      recordAsdMoldUpdate.value = (resFalForm.asdMoldUpdate || {}) as AsdMoldUpdate;

      const res = await await asdMoldFalForm({hid: recordAsdMoldUpdate.value.id});
      record.value = (res.asdMoldFal || {}) as AsdMoldFal;
      record.value.hid = recordAsdMoldUpdate.value.id;
      record.value.__t = new Date().getTime();
      record.value = {
        ...recordAsdMoldUpdate.value.basInv,
        ...recordAsdMoldUpdate.value,
        ...record.value,
      }
    } else {
      resetSchema(inputFormKeepSchemas);
      console.log('inputFormKeepSchemas', inputFormKeepSchemas);
      const res = await asdMoldKeepForm(data);
      record.value = (res.asdMoldKeep || {}) as AsdMoldKeep;
      record.value.__t = new Date().getTime();
      record.value.hid = res.asdMoldKeep?.id;
      console.log('res.asdMoldKeep?.basMold?.useBlQty', record.value.hid);
      record.value.useQty = res.asdMoldKeep?.basMold?.useQty;
      record.value.byQty = res.asdMoldKeep?.basMold?.byQty;
      console.log(res.asdMoldKeep?.basMold?.useBlQty);
      record.value.iqty = res.asdMoldKeep?.basMold?.useQty - res.asdMoldKeep?.basMold?.useBlQty;
      record.value.moldCode ? '' : record.value.moldCode = data['basMold.caddcode']
      record.value.basMold?.name ?? (record.value.basMold = { name: data.name });
      record.value.basMold.caddcode ? '' : record.value.basMold.caddcode = data['moldCode'];
      record.value.basMold.clsCode ? '' : record.value.basMold.clsCode = data['basMold.clsCode'];
      record.value.useQty ? '' : record.value.useQty = data.useQty;
      if (data.byQty) {
        record.value.byQty ? '' : record.value.byQty = data.byQty;
      } else {
        record.value.byQty ? '' : record.value.byQty = 0;
      }
      // record.value.byQty ? '' : record.value.byQty = data.byQty;
      record.value.iqty ? '' : record.value.iqty = data.byQty - data.useBlQty;
    }
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      console.log('submit', data);
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      data.bizKey = formKey.value; // 业务主键
      data.hid = record.value.hid; // 模具ID
      if (formKey.value === 'ASD_MOLD_REPAIR') {
        data.ope = 1;
      } else {
        data.ope = 0;
      }
      console.log('submit', data);
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: true,
        id: '',
      };
      // console.log('submit', params, data, record);
      const res = await asdMoldFalSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }
  async function handleSuccess() {
    emit('success');
  }
</script>
